package com.example.systemserver.Controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.example.systemserver.Bean.ResultBean;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Slf4j
@RestController
public class FileController {


    @RequestMapping("/file/upload")
    public ResultBean upload(@RequestParam("file") MultipartFile  file) throws IOException {
        // 生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = IdUtil.getSnowflakeNextIdStr() + suffix;
        //收到文件之后要将文件保存在硬盘上
        File localFile = new File("C:\\Users\\Administrator\\Desktop\\images\\" + newFileName);
        file.transferTo(localFile);

        String url = "http://localhost:8080/file/download/" + newFileName;
        return new ResultBean(200, "上传成功", url);
    }

    // http://localhost:8080/file/download/xxxx.jpg
    @RequestMapping("/file/download/{filename}")
    public ResultBean download(@PathVariable String filename, HttpServletResponse  response) throws IOException {
        File file = new File("C:\\Users\\Administrator\\Desktop\\images\\" + filename);
        // 和本地文件建立通道
        InputStream is = new FileInputStream(file);
        // 获取到客户端的通道
        OutputStream os = response.getOutputStream();
        // 开始传输数据
        IoUtil.copy(is, os);

        return new ResultBean(200, "下载成功", file);
    }

}